package rhc.taskSchedule.taskSchedule.schedule.schedule;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import rhc.taskSchedule.commander.TaskScheduleCommanderExecute;
import rhc.taskSchedule.entity.RunningType;
import rhc.taskSchedule.entity.Task;
import rhc.taskSchedule.entity.TaskSchedule;
import rhc.taskSchedule.exception.ScheduleException;
import rhc.taskSchedule.taskSchedule.BasicRunning;
import rhc.taskSchedule.taskSchedule.schedule.Schedule;

abstract public class BasicTaskScheduleImpl extends BasicRunning implements Schedule {
	
	/**
	 * 任务分发器
	 */
	protected TaskScheduleCommanderExecute taskScheduleCommanderExecute;
	
	/**
	 * 调度id
	 */
	protected String scheduleId;
	
	protected TaskSchedule taskSchedule;
	
	/**
	 * 运行类型为调度类型
	 */
	protected RunningType runningType=RunningType.SCHEDULE;
	
	/**
	 * 任务id对应的运行id
	 */
	protected Map<String,String> taskId_runningId=new HashMap<String,String>();
	
	public BasicTaskScheduleImpl(String runningId,TaskScheduleCommanderExecute taskScheduleCommanderExecute) throws Exception{
		this.taskScheduleCommanderExecute=taskScheduleCommanderExecute;
		this.runningId=runningId;
		this.currentHost=taskScheduleCommanderExecute.getDistributeNodeCommander().getNodeManage().getCurrentHost();
		initSchedule();
	}
	
	private void initSchedule() throws Exception{
		initRunning();
		scheduleId=running.getSourceId();
		taskSchedule=getTaskSchedule(scheduleId);
	}
	
	@Override
	protected RunningType getRunningType(){
		return runningType;
	}
	
	@Override
	public TaskSchedule getTaskSchedule() throws Exception {
		return taskSchedule;
	}

	@Override
	public List<Task> getAllTask() throws Exception {
		List<String> taskIdList=taskSchedule.getTaskList();
		
		return null;
	}
	
	/**根据调度id获取调度
	 * @param taskScheduleId
	 * @return
	 * @throws Exception
	 */
	protected TaskSchedule getTaskSchedule(String taskScheduleId) throws Exception{
		TaskSchedule taskSchedule=superDao.getOneT(new Query(Criteria.where(TaskSchedule.COLUMN_ID).is(taskScheduleId)), TaskSchedule.class);
		
		if(null == taskSchedule){
			throw new ScheduleException("调度 {} 不存在",taskScheduleId);
		}
		return taskSchedule;
	}
	

	@Override
	public String getSourceId() throws Exception {
		return scheduleId;
	}
	
	@Override
	public String getId() throws Exception {
		return runningId;
	}
	
}
